package com.auth.manager.utils;

import com.auth.manager.pojo.sys.SysMenu;
import com.auth.manager.pojo.sys.TreeMenu;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @Date: 2022/5/2 19:42
 * @Author ZhuYouBin
 * @Description
 */
public class TreeMenuUtil {

    /**
     * 构造权限菜单树
     * @param menuList 权限数据集合
     * @return
     */
    public static List<TreeMenu> buildTreeMenu(List<SysMenu> menuList) {
        if (CollectionUtils.isEmpty(menuList)) {
            return new ArrayList<>();
        }
        List<TreeMenu> treeMenuList = new ArrayList<>();
        // 获取所有顶级权限
        List<SysMenu> topMenuList = menuList.stream().filter(item -> item.getPid() == -1).collect(Collectors.toList());
        for (SysMenu topMenu : topMenuList) {
            TreeMenu topTreeMenu = getTreeMenu(topMenu);
            // 获取子级数据
            List<TreeMenu> menuChildren = getMenuChildren(topTreeMenu, menuList);
            topTreeMenu.setChildren(menuChildren);
            // 添加到结果集合
            treeMenuList.add(topTreeMenu);
        }
        return treeMenuList;
    }

    /**
     * 获取子级数据
     * @param topMenu 顶级数据
     * @param menuList 权限菜单数据集合
     * @return
     */
    public static List<TreeMenu> getMenuChildren(TreeMenu topMenu, List<SysMenu> menuList) {
        // 查找当前顶级菜单的直接下级菜单
        List<SysMenu> subMenuList = menuList.stream().filter(item -> Objects.equals(item.getPid(), topMenu.getMid())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(subMenuList)) {
            return null;
        }
        // 子级菜单
        List<TreeMenu> children = new ArrayList<>();
        for (SysMenu sysMenu : subMenuList) {
            TreeMenu treeMenu = getTreeMenu(sysMenu);
            children.add(treeMenu);
        }
        // 遍历菜单,继续查找子级菜单的下级菜单
        for (TreeMenu child : children) {
            child.setChildren(getMenuChildren(child, menuList));
        }
        return children;
    }

    /**
     * 获取TreeMenu对象
     * @param sysMenu 权限菜单对象
     * @return
     */
    public static TreeMenu getTreeMenu(SysMenu sysMenu) {
        TreeMenu treeMenu = new TreeMenu();
        treeMenu.setMid(sysMenu.getMid());
        treeMenu.setPid(sysMenu.getPid());
        treeMenu.setMenuName(sysMenu.getMenuName());
        treeMenu.setMenuType(sysMenu.getMenuType());
        treeMenu.setMenuIcon(sysMenu.getMenuIcon());
        treeMenu.setUrl(sysMenu.getUrl());
        treeMenu.setComponent(sysMenu.getComponent());
        treeMenu.setMenuKey(sysMenu.getMenuKey());
        treeMenu.setVisible(sysMenu.getVisible());
        treeMenu.setCreateTime(sysMenu.getCreateTime());
        return treeMenu;
    }
}
